#!/bin/bash

######################################################################
# 
# curl -sSL https://gitee.com/xwzhou/utility-scritps/raw/master/docker-rm-unused.sh | bash -s 
#
######################################################################

get_unused_images(){
    local repo=$1
    docker images "$repo" --format '{{.Repository}}:{{.Tag}}' | sort | head -n -5
}

delete_unused_images() {
    echo "$*" | xargs -r docker rmi 
}

main() {
    for repo in $(docker images --format '{{.Repository}}' | sort -u); do
        unused_images=$(get_unused_images "$repo")
        if [ ! -z "$unused_images" ]; then
            delete_unused_images "$unused_images"
        fi
    done
}

main